package com.appcenter.message.service;

import com.appcenter.jz.Logger.BusinessLogger;
import com.appcenter.jz.Logger.LoggerGenre;
import com.appcenter.jz.config.ErrorJsonResult;
import com.appcenter.jz.config.JsonResult;
import com.appcenter.jz.page.PagedResult;
import com.appcenter.message.config.RemoteProperties;
import com.appcenter.message.dto.Apps;
import com.appcenter.message.input.dingconfig.*;
import com.appcenter.message.mapper.DingConfigsMapper;
import com.appcenter.message.model.DingConfigs;
import com.appcenter.message.output.dingconfig.*;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class DingConfigsService {
    @Autowired
    DingConfigsMapper dingConfigMapper;
    @Autowired
    RemoteProperties remoteProperties;
    @Autowired
    private HttpAPIService httpAPIService;
    @Autowired
    ObjectMapper objectMapper;

//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 获取钉钉配置信息
     *  时间: 2019/4/26 14:49 
     *  参数: 
     */
    public CreateDingConfigOutput CreateDingConfig(CreateDingConfigInput input) throws Exception {
        CreateDingConfigOutput output = new CreateDingConfigOutput();

        Example exampleAppCodeCount = new Example(DingConfigs.class);
        Example.Criteria criteria = exampleAppCodeCount.createCriteria();
        criteria.andEqualTo("appCode", input.getItem().getAppCode());
        List<DingConfigs> dingConfigAppCodeCount=dingConfigMapper.selectByExample(exampleAppCodeCount);
        if(dingConfigAppCodeCount.size()>0){
            throw new ErrorJsonResult("1000031","该应用已存在钉钉配置！");
        }
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        DingConfigs config = new DingConfigs();
        config.setId(uuid);
        config.setAppCode(input.getItem().getAppCode());
        config.setTokenUrl(input.getItem().getTokenUrl());
        config.setAgentId(input.getItem().getAgentId());
        config.setPostDingNoticeUrl(input.getItem().getPostDingNoticeUrl());
        config.setOAHeadBgColor("FF37A0D9");
        dingConfigMapper.insertSelective(config);
        BusinessLogger.Info(LoggerGenre.Add, "添加钉钉配置信息", input);
        output.setItem(config);
        return output;
    }
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 删除钉钉配置信息
     *  时间: 2019/4/26 14:49 
     *  参数: 
     */
    public DeleteDingConfigOutput DeleteDingConfig(DeleteDingConfigInput input) throws Exception {
        DeleteDingConfigOutput output = new DeleteDingConfigOutput();
        DingConfigs oldApps=dingConfigMapper.selectByPrimaryKey(input.getItem().getId());
        dingConfigMapper.deleteByPrimaryKey(oldApps);
        BusinessLogger.Info(LoggerGenre.Delete, "删除钉钉配置信息", input);
        return output;
    }
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 修改钉钉配置
     *  时间: 2019/4/26 14:49 
     *  参数: 
     */
    public EditDingConfigOutput EditDingConfig(EditDingConfigInput input) throws Exception {
        EditDingConfigOutput output=new EditDingConfigOutput();
        Example exampleAppCodeCount = new Example(DingConfigs.class);
        Example.Criteria criteria = exampleAppCodeCount.createCriteria();
        criteria.andEqualTo("appCode", input.getItem().getAppCode());
        criteria.andNotEqualTo("id",input.getItem().getId());
        List<DingConfigs> dingConfigAppCodeCount=dingConfigMapper.selectByExample(exampleAppCodeCount);
        if(dingConfigAppCodeCount.size()>0){
            throw new ErrorJsonResult("1000031","该应用已存在钉钉配置！");
        }
        DingConfigs config= dingConfigMapper.selectByPrimaryKey(input.getItem().getId());
        config.setAppCode(input.getItem().getAppCode());
        config.setTokenUrl(input.getItem().getTokenUrl());
        config.setAgentId(input.getItem().getAgentId());
        config.setPostDingNoticeUrl(input.getItem().getPostDingNoticeUrl());
        dingConfigMapper.updateByPrimaryKey(config);
        BusinessLogger.Info(LoggerGenre.Update, "更新钉钉配置信息", input);
        output.setItem(config);
        return  output;
    }
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 获取钉钉配置
     *  时间: 2019/4/26 14:49 
     *  参数: 
     */
    public GetDingConfigsOutput GetDingConfigs(GetDingConfigsInput input) throws Exception {


        GetDingConfigsOutput output = new GetDingConfigsOutput();
        PageHelper.startPage(input.getPage().getPageNo(),input.getPage().getPageSize(),"id desc");
        List<DingConfigs> ls = dingConfigMapper.SearchDingConfigs(input);
        //List<Apps> ls=AppMapper.selectAll();
        //Example example = new Example(Apps.class);
        //Example.Criteria criteria = example.createCriteria();
        //criteria.andEqualTo("ValidStatus", 1);
        //List<Apps> ls=AppMapper.selectByExample(example);

        output.setItems(new PagedResult<DingConfigs>(ls, ls.size()));
        BusinessLogger.Info(LoggerGenre.View, "获取钉钉配置信息", input);
        return  output;
    }
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 加载钉钉配置
     *  时间: 2019/4/26 14:49 
     *  参数: 
     */
    public PageLoadOutput PageLoad(PageLoadInput input) throws Exception {
        PageLoadOutput output = new PageLoadOutput();
        output.setItems(GetDingConfigs(input).getItems());


        String GetAppsUrl = remoteProperties.getAppCenterServiceUrl()+"/app/getapps";
        String responseJson = httpAPIService.JsonSMS(GetAppsUrl, "{}");
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JsonResult jsonResult = objectMapper.readValue(responseJson, JsonResult.class);

        List<Apps> apps=new ArrayList<Apps>();
        Object OneItems=JsonUnit(jsonResult.getResult(),"items");
        ArrayList<Object> TwoItems= (ArrayList<Object>) JsonUnit(OneItems,"items");
        if(TwoItems!=null && TwoItems.size()>0){
            for (int i = 0; i < TwoItems.size(); i++) {
                Apps app = new Apps();
                app.setId(JsonUnit(TwoItems.get(i),"id").toString());
                app.setAppCode(JsonUnit(TwoItems.get(i),"appCode").toString());
                app.setAppName(JsonUnit(TwoItems.get(i),"appName").toString());
                apps.add(app);
            }
        }
        output.setApps(apps);

        return output;
    }
    /**
     *  创建人:Coke
     *  备注: 根据APPCode获取钉钉配置信息
     *  时间: 2019/4/26 15:02
     *  参数: 
     */
    public DingConfigs getDingConfig(String AppCode) {
        return dingConfigMapper.getDingConfig(AppCode);
    }

    public Object JsonUnit(Object a,String Key){
        Map map = (Map) a;
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            if(entry.getKey().toString().equals(Key)){
                return entry.getValue();
            }
        }
        return null;
    }
}
